package com.huawei.aw;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * AWHttpUtil：封装常用的 HTTP 请求（GET/POST/PUT）
 * 基于 Java 11+ 内置 HttpClient，无需额外 HTTP 库
 * 自动过滤受限请求头（如 Connection、Host 等），避免 IllegalArgumentException
 */
public class AWHttpUtil {

    // JSON 序列化/反序列化工具（线程安全）
    private static final ObjectMapper objectMapper = new ObjectMapper();

    // HTTP 客户端（线程安全，全局复用）
    private static final HttpClient httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

    // 受限请求头列表（Java HttpClient 不允许手动设置）
    private static final Set<String> RESTRICTED_HEADERS = new HashSet<>(Arrays.asList(
            "connection", "host", "content-length", "upgrade",
            "transfer-encoding", "keep-alive", "proxy-connection"
    ));

    /**
     * 安全设置请求头：自动跳过受限头字段
     */
    private static void safeSetHeaders(HttpRequest.Builder builder, Map<String, String> headers) {
        if (headers == null || headers.isEmpty()) {
            return;
        }
        headers.forEach((name, value) -> {
            if (name != null && value != null) {
                String lowerName = name.toLowerCase().trim();
                if (!RESTRICTED_HEADERS.contains(lowerName)) {
                    builder.header(name, value);
                }
            }
        });
    }

    // ==================== GET ====================

    /**
     * 发送 GET 请求（无自定义头）
     */
    public static String get(String url) throws Exception {
        return get(url, null);
    }

    /**
     * 发送 GET 请求（带自定义头）
     */
    public static String get(String url, Map<String, String> headers) throws Exception {
        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .timeout(Duration.ofSeconds(30))
                .GET();

        safeSetHeaders(requestBuilder, headers);
        HttpRequest request = requestBuilder.build();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        return response.body();
    }

    // ==================== POST ====================

    /**
     * 发送 POST 请求（自动序列化 body 为 JSON）
     */
    public static String post(String url, Object body) throws Exception {
        return post(url, body, null);
    }

    /**
     * 发送 POST 请求（带自定义头）
     */
    public static String post(String url, Object body, Map<String, String> headers) throws Exception {
        String jsonBody = body instanceof String ? (String) body : objectMapper.writeValueAsString(body);

        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .timeout(Duration.ofSeconds(30))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonBody));

        safeSetHeaders(requestBuilder, headers);
        HttpRequest request = requestBuilder.build();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        return response.body();
    }

    // ==================== PUT ====================

    /**
     * 发送 PUT 请求（自动序列化 body 为 JSON）
     */
    public static String put(String url, Object body) throws Exception {
        return put(url, body, null);
    }

    /**
     * 发送 PUT 请求（带自定义头）
     */
    public static String put(String url, Object body, Map<String, String> headers) throws Exception {
        String jsonBody = body instanceof String ? (String) body : objectMapper.writeValueAsString(body);

        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .timeout(Duration.ofSeconds(30))
                .header("Content-Type", "application/json")
                .PUT(HttpRequest.BodyPublishers.ofString(jsonBody));

        safeSetHeaders(requestBuilder, headers);
        HttpRequest request = requestBuilder.build();
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        return response.body();
    }
}